package neu.competition.controller;

import lombok.extern.slf4j.Slf4j;
import neu.competition.dto.CompetitionsDTO;
import neu.competition.dto.MatchesDTO;
import neu.competition.dto.TeamDTO;
import neu.competition.dto.UserDTO;
import neu.competition.service.CompetitionsService;
import neu.competition.service.MatchesService;
import neu.competition.service.TeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@Slf4j
@RequestMapping("/competition")
public class CompetitionController {
    @Autowired
    TeamService ts;
    @Autowired
    private CompetitionsService competitionsService;
    @Autowired
    private MatchesService matchesService;

    /**
     * 创办赛事
     *
     * @return
     */
    @RequestMapping("/addCompetition")
    public String createCompetition() {
        return "/competition/create-competition";
    }

    @RequestMapping("/insertCompetition")
    public String insertCompetition(CompetitionsDTO competitionsDTO,
                                    @RequestParam("fileUpload") MultipartFile fileUpload,
                                    RedirectAttributes redirectAttributes,
                                    @RequestParam("fileUpload1") MultipartFile fileUpload1, HttpSession session) {
        try {
            // 设置上传文件的保存地址目录
            File directory = new File("src/main/resources");
            String reportPath = directory.getCanonicalPath();
            String path = "/static/images/poster/";
            String dirPath = reportPath + path;
            File filePath = new File(dirPath);
            //目录不存在就创建目录
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            //获取文件名
            String fileName = fileUpload.getOriginalFilename();
            String fileName1 = fileUpload1.getOriginalFilename();
            fileUpload.transferTo(new File(dirPath + fileName));
            fileUpload1.transferTo(new File(dirPath + fileName1));
            competitionsDTO.setComlogo("/images/poster/" + fileName1);
            competitionsDTO.setEventpictures("/images/poster/" + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/competition/my-competition";
        }
        /**
         * 判断比赛是否重复
         */
        try {
            // 检查是否有重复的赛事
            if (competitionsService.isDuplicate(competitionsDTO)) {
                // 如果发现重复，添加错误消息并重定向回表单
                redirectAttributes.addFlashAttribute("errorMessage", "发现重复的赛事。");
                redirectAttributes.addFlashAttribute("competitionsDTO", competitionsDTO);
                return "redirect:/competition/create";
            }
            // 插入赛事

            redirectAttributes.addFlashAttribute("successMessage", "赛事创建成功。");
        } catch (Exception e) {
            log.error("创建赛事时存在相同的赛事: {}", e.getMessage());
            return "common/Error";
        }
        UserDTO us = (UserDTO) session.getAttribute("USER_INFO");
        competitionsService.insert(competitionsDTO, us.getUserid());
        return "redirect:/competition/my-competition";
    }

    @GetMapping("/competition-details")//赛事详情
    public String competitionDetails(Model model, Integer comId) {
        CompetitionsDTO DTO = competitionsService.getCompetitionDTOSById(comId);
        model.addAttribute("dto", DTO);

        MatchesDTO matchesDTO = matchesService.getMatchById(DTO.getLastest());
        List<MatchesDTO> matchList=new ArrayList<>();
        matchList=matchesService.getMatchListByComId(comId);
        for (MatchesDTO matches : matchList) {
            if (matches.equals(matchesDTO)) {
                matchesDTO.setNumber(matchList.indexOf(matchesDTO) + 1);
                matchesDTO.setComname(competitionsService.getCompetitionDTOSById(comId).getComname());
            }
        }
        model.addAttribute("match", matchesDTO);


        return "/competition/competition-details";
    }

    @RequestMapping("/addMatch")
    public String createRace(Integer comId, Model model) {
        CompetitionsDTO competitionsDTO = competitionsService.getCompetitionDTOSById(comId);
        model.addAttribute("competition", competitionsDTO);
        return "competition/add-match";
    }

    /**
     * 添加比赛
     *
     * @param matchesDTO
     * @return
     */
    @PostMapping("/insertMatch")
    public String insertRace(MatchesDTO matchesDTO, @RequestParam("fileUpload") MultipartFile fileUpload
            , HttpSession session) {
        try {
            // 设置上传文件的保存地址目录
            File directory = new File("src/main/resources");
            String reportPath = directory.getCanonicalPath();
            String path = "/static/images/poster/";
            String dirPath = reportPath + path;
            File filePath = new File(dirPath);
            //目录不存在就创建目录
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            //获取文件名
            String fileName = fileUpload.getOriginalFilename();

            fileUpload.transferTo(new File(dirPath + fileName));
            UserDTO us = (UserDTO) session.getAttribute("USER_INFO");
            matchesDTO.setPoster("/images/poster/" + fileName);
            matchesService.insert(matchesDTO, us.getUserid());
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:competition/add-match";
        }


        return "redirect:/competition/my-match";
    }

    @GetMapping("/my-match")//我的比赛
    public String myRace(Model model, HttpSession session) {
        UserDTO u = (UserDTO) session.getAttribute("USER_INFO");
        List<MatchesDTO> matchesDTOS = matchesService.getMatchesListByUserId(u.getUserid());

        for (MatchesDTO matchesDTO : matchesDTOS) {
            matchesDTOS.indexOf(matchesDTO);
            Map<Integer, List<MatchesDTO>> groupedByComId = matchesDTOS.stream()
                    .collect(Collectors.groupingBy(MatchesDTO::getComid));
            List<MatchesDTO> list = groupedByComId.get(matchesDTO.getComid());
            matchesDTO.setNumber(list.indexOf(matchesDTO) + 1);
            matchesDTO.setComname(competitionsService.getCompetitionDTOSById(matchesDTO.getComid()).getComname());
        }
        model.addAttribute("matchesDTOS", matchesDTOS);
        return "/competition/my-match";
    }

    @GetMapping("/my-competition")//我的赛事
    public String myCompetition(Model model, HttpSession session) {
        UserDTO u = (UserDTO) session.getAttribute("USER_INFO");
        List<CompetitionsDTO> competitionsDTOS = competitionsService.getCompetitionSDotListByUserId(u.getUserid());
        model.addAttribute("competitionsDTOS", competitionsDTOS);
        return "/competition/my-competition";
    }

    @GetMapping("/select-competition")//选择赛事
    public String selectCompetition(Model model) {
        List<CompetitionsDTO> competitionsDTOS = competitionsService.getAllCompetitionsDTOList();
        model.addAttribute("competitionsDTOS", competitionsDTOS);
        return "/competition/select-competition";
    }

    @GetMapping("/match-details")//比赛详情
    public String raceDetails(HttpSession session, Model model, Integer id) {
        MatchesDTO matchesDTO = matchesService.getMatchById(id);


        CompetitionsDTO competitionsDTO = competitionsService.getCompetitionDTOSById(matchesDTO.getComid());
        List<MatchesDTO> matchList = matchesService.getMatchListByComId(competitionsDTO.getComid());

        model.addAttribute("matches", matchesDTO);
        model.addAttribute("competitions", competitionsDTO);
        if (matchesDTO.getStatecompetition() == 0) {
            return "competition/match-details";
        } else {
            String res = "1";
            UserDTO u = (UserDTO) session.getAttribute("USER_INFO");
            if (matchesService.isSignedup(matchesDTO.getMatchid(), matchesDTO.getComid(), u.getUserid()))
                res = "0";
            model.addAttribute("ok", res);
            return "competition/match-details-only";
        }

    }

    @GetMapping("/login")//首页
    public String Login(Model model) {
        List<CompetitionsDTO> list = competitionsService.getCompetitionSDotListByUserId("1");
        model.addAttribute("competitionsDTOS", list);
        return "competition/competition-login";
    }

    @RequestMapping("updateMatch")
    public String updateMatch(MatchesDTO matchesDTO) {
        int i = matchesService.updateMatch(matchesDTO);
        return "redirect:/competition/my-match";
    }

    @RequestMapping("/search")
    public String search(String keyword, Model model) {
        List<CompetitionsDTO> competitionsDTO = competitionsService.getCompetitionSDotList(keyword);
        model.addAttribute("keyword", keyword);
        model.addAttribute("competitionsDTOS", competitionsDTO);
        return "/competition/result";
    }

    @RequestMapping("/commitMatch")
    private String commitMatch(Integer matchId) {
        int i = matchesService.matchUpdateStateCompetition(matchId);
        MatchesDTO matchesDTO = matchesService.getMatchById(matchId);
        competitionsService.UpdateCompetitionsLastest(matchesDTO.getComid(), matchId);
        System.out.println(i);
        return "redirect:/competition/my-match";
    }

    @RequestMapping("/reg")
    public String SignUpCompetition(Integer matchid, HttpSession session, Model model) {
        UserDTO u = (UserDTO) session.getAttribute("USER_INFO");
        List<TeamDTO> tds = ts.SelectTeamsByUserID(u.getUserid());
        model.addAttribute("teams", tds);
        MatchesDTO DTO = matchesService.getMatchById(matchid);
        System.out.println(DTO);
        model.addAttribute("dto", DTO);
        return "/competition/baoming";
    }

    @PostMapping("/signup")
    @ResponseBody
    public Map Signup(int mid, int cid, int tid, HttpSession session, Model model) {
        UserDTO u = (UserDTO) session.getAttribute("USER_INFO");
        System.out.println(mid);
        System.out.println(cid);
        System.out.println(tid);
        boolean res = matchesService.SignUp(mid, cid, tid);
        Map<String, String> mp = new HashMap<>();
        if (res)
            mp.put("result", "success");
        else
            mp.put("result", "error");
        return mp;
    }
}